//
//  DMBannerSceneManager.m
//  DualMediationSDK
//
//  Created by DualMediation on 2024/01/01.
//  Copyright © 2024 DualMediation. All rights reserved.
//

#import "DMBannerSceneManager.h"
#import "DMBannerStrategyParser.h"
#import "../DMBannerScenes.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../IronSource/DMBannerManager.h"
#import "../MAX/DualMediationMAXBannerManager.h"
#import "../../API/AdStrategy/IMAdStrategyManager.h"
#import "../../API/AdStrategy/IMSDKStartupConfigManager.h"
#import "../../DualMediationSDKPublic.h"

@interface DMBannerSceneManager ()

/**
 * 策略解析器
 */
@property (nonatomic, strong) DMBannerStrategyParser *strategyParser;

/**
 * 当前关卡
 */
@property (nonatomic, assign) NSInteger currentLevel;

/**
 * 当前展示的Banner场景
 */
@property (nonatomic, strong) NSMutableSet<NSString *> *activeBannerScenes;

/**
 * 场景展示时间记录
 */
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *sceneShowTimes;

@end

@implementation DMBannerSceneManager

#pragma mark - 单例

+ (instancetype)sharedManager {
    static DMBannerSceneManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMBannerSceneManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _sceneManagerEnabled = YES;
        _strategyParser = [DMBannerStrategyParser sharedParser];
        _currentLevel = 1; // 默认关卡
        _activeBannerScenes = [NSMutableSet set];
        _sceneShowTimes = [NSMutableDictionary dictionary];
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [BannerSceneManager] Banner场景管理器初始化完成"];
        
        // 初始化时获取Banner策略数据
        [self initializeBannerStrategies];
    }
    return self;
}

#pragma mark - 公共接口



- (BOOL)showBannerForScene:(NSString *)sceneName
                  position:(BannerPosition)position
    enableShortScreenDetection:(BOOL)enableShortScreenDetection
             containerView:(UIView * _Nullable)containerView {
    
    if (!self.sceneManagerEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [BannerSceneManager] 场景管理器已禁用，跳过Banner展示"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示Banner广告 - 场景: %@, 位置: %ld, 短屏检测: %@", 
     sceneName ?: @"未指定", (long)position, enableShortScreenDetection ? @"启用" : @"禁用"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: 场景名称为空"];
        return NO;
    }
    
    // 检查展示条件
    if (![self canShowBannerForScene:sceneName]) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ Banner展示条件不满足 - 场景: %@", sceneName];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    BOOL success = NO;
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        DMBannerScene scene = [self bannerSceneFromString:sceneName];
        [bannerManager showBannerAd:scene position:position enableShortScreenDetection:enableShortScreenDetection];
        success = YES;
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告展示 - 场景: %@", sceneName];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        [maxBannerManager showBannerAd:sceneName position:position enableShortScreenDetection:enableShortScreenDetection];
        success = YES;
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告展示 - 场景: %@", sceneName];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: 不支持的SDK类型 %@", sdkType];
        return NO;
    }
    
    if (success) {
        [self.activeBannerScenes addObject:sceneName];
        [self recordBannerShowForScene:sceneName];
        [IMLogUtils info:IMLogTagAd format:@"✅ Banner展示请求成功 - 场景: %@", sceneName];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner展示请求失败 - 场景: %@", sceneName];
    }
    
    return success;
}

- (void)showBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示Banner - 场景: %@", sceneName];
    
    // 检查免广告状态
    if ([[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeBanner]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 Banner广告已被禁用，跳过展示 - 场景: %@", sceneName];
        return;
    }
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner展示失败: 场景名称为空"];
        return;
    }
    
    // 使用默认配置展示Banner
    BannerPosition position = [self getBannerPositionForScene:sceneName];
    BOOL enableShortScreenDetection = [self isShortScreenDetectionEnabledForScene:sceneName];
    
    [self showBannerForScene:sceneName position:position enableShortScreenDetection:enableShortScreenDetection containerView:nil];
}

- (void)showBannerAd:(NSString *)sceneValue 
            position:(BannerPosition)position 
enableShortScreenDetection:(BOOL)enableShortScreenDetection {
    // 检查广告是否被禁用
    if ([[DualMediationSDKPublic sharedInstance] isRemoveAd:DMAdBanTypeBanner]) {
        [IMLogUtils info:IMLogTagAd format:@"🚫 Banner广告已禁用，跳过展示 - 场景: %@", sceneValue ?: @"未指定"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🏷️ 展示Banner广告 - 场景: %@, 位置: %ld, 短屏检测: %@", 
     sceneValue, (long)position, enableShortScreenDetection ? @"启用" : @"禁用"];
    
    if (!sceneValue || sceneValue.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告展示失败: 场景值为空"];
        return;
    }
    
    [self showBannerForScene:sceneValue position:position enableShortScreenDetection:enableShortScreenDetection containerView:nil];
}

- (void)hideBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🙈 隐藏Banner广告 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: 场景名称为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        DMBannerScene scene = [self bannerSceneFromString:sceneName];
        [bannerManager hideBannerForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告隐藏 - 场景: %@", sceneName];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        [maxBannerManager hideBannerForScene:sceneName];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告隐藏 - 场景: %@", sceneName];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告隐藏失败: 不支持的SDK类型 %@", sdkType];
        return;
    }
    
    [self.activeBannerScenes removeObject:sceneName];
    [IMLogUtils info:IMLogTagAd format:@"✅ Banner隐藏完成 - 场景: %@", sceneName];
}

- (BOOL)isBannerReadyForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🔍 检查Banner广告状态 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查Banner广告状态失败: 场景名称为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ 检查Banner广告状态失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    BOOL isReady = NO;
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        DMBannerScene scene = [self bannerSceneFromString:sceneName];
        isReady = [bannerManager isBannerReadyForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告状态检查 - 场景: %@", sceneName];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        isReady = [maxBannerManager isBannerReadyForScene:sceneName];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告状态检查 - 场景: %@", sceneName];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告状态检查失败: 不支持的SDK类型 %@", sdkType];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 Banner状态 - 场景: %@, 状态: %@", sceneName, isReady ? @"已准备" : @"未准备"];
    
    return isReady;
}

- (BOOL)preloadBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"⏳ 预加载Banner广告 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告预加载失败: 场景名称为空"];
        return NO;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告预加载失败: sdk_config_sdk_type配置为空"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    BOOL success = NO;
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        DMBannerScene scene = [self bannerSceneFromString:sceneName];
        [bannerManager preloadBannerForScene:scene];
        success = YES;
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告预加载 - 场景: %@", sceneName];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        [maxBannerManager preloadBannerForScene:sceneName];
        success = YES;
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告预加载 - 场景: %@", sceneName];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告预加载失败: 不支持的SDK类型 %@", sdkType];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"%@ Banner预加载 - 场景: %@", success ? @"✅" : @"❌", sceneName];
    
    return success;
}

- (void)destroyBannerForScene:(NSString *)sceneName {
    [IMLogUtils info:IMLogTagAd format:@"🗑️ 销毁Banner广告 - 场景: %@", sceneName ?: @"未指定"];
    
    if (!sceneName || sceneName.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告销毁失败: 场景名称为空"];
        return;
    }
    
    // 获取SDK配置类型
    IMSDKStartupConfig *config = [[IMAdStrategyManager sharedManager] getSDKStartupConfig];
    NSString *sdkType = config.sdk_config_sdk_type;
    
    if (!sdkType || sdkType.length == 0) {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告销毁失败: sdk_config_sdk_type配置为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📋 当前SDK类型: %@", sdkType];
    
    if ([sdkType isEqualToString:@"IS"] || [sdkType isEqualToString:@"IS&MAX"]) {
        // 使用IronSource Banner广告管理器
        DMBannerManager *bannerManager = [DMBannerManager shareBannerManager];
        DMBannerScene scene = [self bannerSceneFromString:sceneName];
        [bannerManager destroyBannerForScene:scene];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用IronSource Banner广告销毁 - 场景: %@", sceneName];
    } else if ([sdkType isEqualToString:@"MAX"]) {
        // 使用MAX Banner广告管理器
        DualMediationMAXBannerManager *maxBannerManager = [DualMediationMAXBannerManager sharedBannerManager];
        [maxBannerManager destroyBannerForScene:sceneName];
        [IMLogUtils info:IMLogTagAd format:@"✅ 调用MAX Banner广告销毁 - 场景: %@", sceneName];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"❌ Banner广告销毁失败: 不支持的SDK类型 %@", sdkType];
        return;
    }
    
    [self.activeBannerScenes removeObject:sceneName];
    [self.sceneShowTimes removeObjectForKey:sceneName];
    [IMLogUtils info:IMLogTagAd format:@"✅ Banner销毁完成 - 场景: %@", sceneName];
}

- (void)updateCurrentLevel:(NSInteger)level {
    self.currentLevel = level;
    [IMLogUtils info:IMLogTagAd format:@"📊 更新当前关卡: %ld", (long)level];
}

- (NSInteger)getCurrentLevel {
    return self.currentLevel;
}

- (void)recordBannerShowForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        return;
    }
    
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    self.sceneShowTimes[sceneName] = @(currentTime);
    [IMLogUtils info:IMLogTagAd format:@"📊 记录Banner展示 - 场景: %@, 时间: %.0f", sceneName, currentTime];
}

- (BOOL)canShowBannerForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        return NO;
    }
    
    // 获取上次展示时间
    NSNumber *lastShowTimeNumber = self.sceneShowTimes[sceneName];
    NSTimeInterval lastShowTime = lastShowTimeNumber ? lastShowTimeNumber.doubleValue : 0;
    
    // 使用策略解析器检查条件
    BOOL canShow = [self.strategyParser canShowBannerScene:sceneName 
                                              currentLevel:self.currentLevel 
                                              lastShowTime:lastShowTime];
    
    [IMLogUtils info:IMLogTagAd format:@"🔍 Banner展示条件检查 - 场景: %@, 结果: %@", sceneName, canShow ? @"满足" : @"不满足"];
    
    return canShow;
}

- (BannerPosition)getBannerPositionForScene:(NSString *)sceneName {
    NSString *positionString = [self.strategyParser getBannerPositionForScene:sceneName];
    
    if ([positionString isEqualToString:@"top"]) {
        return BannerPositionTop;
    } else if ([positionString isEqualToString:@"bottom_top"]) {
        return BannerPositionBottomTop;
    } else {
        return BannerPositionBottom; // 默认底部
    }
}

- (BOOL)isShortScreenDetectionEnabledForScene:(NSString *)sceneName {
    return [self.strategyParser isBannerShortShowEnabledForScene:sceneName];
}

- (void)clearAllSceneData {
    [IMLogUtils info:IMLogTagAd format:@"🗑️ 清除所有Banner场景数据"];
    [self.activeBannerScenes removeAllObjects];
    [self.sceneShowTimes removeAllObjects];
    [self.strategyParser clearAllStrategies];
}







#pragma mark - 私有方法 - 动态初始化

// 移除ensureBannerManagersInitialized方法，因为现在使用动态选择逻辑

#pragma mark - 私有方法 - 事件记录

/**
 * 记录展示事件（用于统计和分析）
 */
- (void)recordShowEventForScene:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📊 记录Banner展示事件 - 场景: %@", sceneName];
    
    // 这里可以添加具体的事件记录逻辑，比如发送到分析平台
    // 目前只做日志记录
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    [IMLogUtils info:IMLogTagAd format:@"📊 Banner展示事件已记录 - 场景: %@, 时间戳: %.0f", sceneName, currentTime];
}

#pragma mark - 私有方法 - Banner管理器初始化

// 移除initializeBannerManagers方法，因为现在使用动态选择逻辑

#pragma mark - 私有方法 - 策略初始化

/**
 * 初始化Banner策略数据
 * 在DMBannerSceneManager初始化时调用，从广告策略接口获取真实策略数据
 */
- (void)initializeBannerStrategies {
    [IMLogUtils info:IMLogTagAd format:@"🔄 开始初始化Banner策略数据"];
    
    // 使用DMBannerStrategyParser从广告策略接口获取策略数据
    [self.strategyParser fetchAndParseBannerStrategyWithCompletion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [IMLogUtils info:IMLogTagAd format:@"✅ Banner策略初始化成功"];
        } else {
            [IMLogUtils error:IMLogTagAd format:@"❌ Banner策略初始化失败: %@", error.localizedDescription ?: @"未知错误"];
            // 策略初始化失败时，DMBannerStrategyParser会使用默认配置，不影响Banner功能
        }
    }];
}


#pragma mark - 辅助方法

/**
 * 将NSString场景名称转换为DMBannerScene枚举
 * @param sceneName 场景名称字符串
 * @return DMBannerScene枚举值
 */
- (DMBannerScene)bannerSceneFromString:(NSString *)sceneName {
    if (!sceneName || sceneName.length == 0) {
        return DMBannerSceneInit; // 默认场景
    }
    
    if ([sceneName isEqualToString:SCENE_BANNER_INIT]) {
        return DMBannerSceneInit;
    } else if ([sceneName isEqualToString:SCENE_BANNER_LEVEL_ENTER]) {
        return DMBannerSceneLevelEnter;
    } else if ([sceneName isEqualToString:SCENE_BANNER_LEVEL_WIN]) {
        return DMBannerSceneLevelComplete;
    } else if ([sceneName isEqualToString:SCENE_BANNER_SHOP]) {
        return DMBannerSceneShop;
    } else if ([sceneName isEqualToString:SCENE_BANNER_LEVEL_FAIL]) {
        return DMBannerSceneLevelFail;
    } else if ([sceneName isEqualToString:SCENE_BANNER_GAME_PAUSE]) {
        return DMBannerSceneGamePause;
    } else if ([sceneName isEqualToString:SCENE_BANNER_MAIN_MENU]) {
        return DMBannerSceneMainMenu;
    } else if ([sceneName isEqualToString:SCENE_BANNER_SETTINGS]) {
        return DMBannerSceneSettings;
    } else {
        // 对于未知场景，返回默认场景
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ 未知Banner场景: %@，使用默认场景", sceneName];
        return DMBannerSceneInit;
    }
}
@end
